"""
AI评估任务监控管理命令
"""
import logging
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.db import transaction
from datetime import timedelta
from resume_management.models import Resume
from resume_management.tasks import send_evaluation_notification

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Monitor and manage AI evaluation tasks'

    def add_arguments(self, parser):
        parser.add_argument(
            '--cleanup',
            action='store_true',
            help='Clean up stuck evaluation tasks',
        )
        parser.add_argument(
            '--status',
            action='store_true',
            help='Show evaluation task status',
        )
        parser.add_argument(
            '--timeout',
            type=int,
            default=10,
            help='Timeout in minutes for stuck tasks (default: 10)',
        )

    def handle(self, *args, **options):
        if options['cleanup']:
            self.cleanup_stuck_tasks(options['timeout'])
        elif options['status']:
            self.show_status()
        else:
            self.stdout.write(
                self.style.WARNING('Please specify --cleanup or --status')
            )

    def cleanup_stuck_tasks(self, timeout_minutes):
        """清理卡住的评估任务"""
        self.stdout.write(f'正在清理超过 {timeout_minutes} 分钟的卡住任务...')
        
        stuck_time = timezone.now() - timedelta(minutes=timeout_minutes)
        stuck_resumes = Resume.objects.filter(
            ai_evaluation_status='in_progress',
            updated_at__lt=stuck_time
        ).select_related('student', 'student__user')
        
        count = 0
        for resume in stuck_resumes:
            try:
                with transaction.atomic():
                    resume.ai_evaluation_status = 'failed'
                    resume.ai_evaluation_error = f'评估任务超时（超过{timeout_minutes}分钟），已自动重置'
                    resume.save()
                
                # 发送通知
                try:
                    student_user = resume.student.user if hasattr(resume.student, 'user') else None
                    if student_user:
                        send_evaluation_notification(
                            student_user, resume, None, 'failed', 
                            f'评估任务超时，请重新尝试评估'
                        )
                        self.stdout.write(f'  ✓ 已发送通知给用户: {student_user.username}')
                except Exception as e:
                    self.stdout.write(
                        self.style.WARNING(f'  ⚠ 发送通知失败 - Resume ID: {resume.id}, Error: {e}')
                    )
                
                count += 1
                self.stdout.write(
                    self.style.SUCCESS(f'  ✓ 重置任务 - Resume ID: {resume.id}, 简历: {resume.title}')
                )
                
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(f'  ✗ 重置失败 - Resume ID: {resume.id}, Error: {e}')
                )
        
        if count > 0:
            self.stdout.write(
                self.style.SUCCESS(f'清理完成，共重置 {count} 个卡住的评估任务')
            )
        else:
            self.stdout.write('没有发现卡住的评估任务')

    def show_status(self):
        """显示评估任务状态"""
        self.stdout.write('AI评估任务状态统计:')
        self.stdout.write('=' * 50)
        
        # 统计各状态的任务数量
        status_counts = {}
        for status_choice in Resume.AI_EVALUATION_STATUS_CHOICES:
            status = status_choice[0]
            count = Resume.objects.filter(ai_evaluation_status=status).count()
            status_counts[status] = count
        
        # 显示统计结果
        for status, count in status_counts.items():
            status_name = dict(Resume.AI_EVALUATION_STATUS_CHOICES).get(status, status)
            if status == 'in_progress' and count > 0:
                self.stdout.write(
                    self.style.WARNING(f'  {status_name}: {count}')
                )
            elif status == 'failed' and count > 0:
                self.stdout.write(
                    self.style.ERROR(f'  {status_name}: {count}')
                )
            elif status == 'completed' and count > 0:
                self.stdout.write(
                    self.style.SUCCESS(f'  {status_name}: {count}')
                )
            else:
                self.stdout.write(f'  {status_name}: {count}')
        
        # 显示进行中的任务详情
        in_progress_tasks = Resume.objects.filter(
            ai_evaluation_status='in_progress'
        ).select_related('student').order_by('updated_at')
        
        if in_progress_tasks.exists():
            self.stdout.write('\n进行中的任务详情:')
            self.stdout.write('-' * 50)
            
            now = timezone.now()
            for resume in in_progress_tasks:
                elapsed = now - resume.updated_at
                elapsed_minutes = int(elapsed.total_seconds() / 60)
                
                status_style = self.style.WARNING
                if elapsed_minutes > 30:
                    status_style = self.style.ERROR
                
                self.stdout.write(
                    status_style(
                        f'  Resume ID: {resume.id}, 简历: {resume.title}, '
                        f'学生: {resume.student.name}, 运行时间: {elapsed_minutes}分钟'
                    )
                )
        
        # 显示最近失败的任务
        recent_failed = Resume.objects.filter(
            ai_evaluation_status='failed',
            updated_at__gte=timezone.now() - timedelta(hours=24)
        ).select_related('student').order_by('-updated_at')[:5]
        
        if recent_failed.exists():
            self.stdout.write('\n最近24小时失败的任务:')
            self.stdout.write('-' * 50)
            
            for resume in recent_failed:
                self.stdout.write(
                    self.style.ERROR(
                        f'  Resume ID: {resume.id}, 简历: {resume.title}, '
                        f'学生: {resume.student.name}, 错误: {resume.ai_evaluation_error or "未知错误"}'
                    )
                )
